<template>
    <div style="width: 100%;height: 100vh;background-color: steelblue; overflow: hidden;">
        <div style="width: 400px; margin: 150px auto;">
            <div style="color: white; font-size: 30px; text-align: center; padding: 30px 0;">欢迎登录</div>
            <el-form ref="loginForm" :model="form" label-width="auto" :rules="rules" style="max-width: 400px">
                <el-form-item prop="username">
                    <el-input   prefix-icon="Avatar" v-model="form.username">
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input  prefix-icon="Lock" v-model="form.password" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button style="width: 100%;" type="primary" @click="login(loginForm)">登录</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button style="width: 100%;" type="primary" @click="$router.push('/register')">注册</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup name="Login">
import { reactive, ref } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import request from '../utils/request';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import router from '../router';




interface RuleForm {
    username: string,
    password: string
}
const loginForm = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ]
})


let form = reactive({
    username: '',
    password: ''
})


function login(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            request.post('/user/login', form).then(res => {
                if (res.code === '0') {
                    ElMessage({
                        message: '登录成功',
                        type: 'success'
                    })
                sessionStorage.setItem("user", JSON.stringify(form))
                router.push('/') //登录成功之后进行页面跳转                                   
                }
                else {
                    ElMessage({
                        message: res.msg,
                        type: 'error'
                    })
                }
            })

        } else {
            console.log('error submit!')
        }
    })
}

</script>